// Copyright (c) 2023 坚果派
// 公众号：nutpi
// 电话：17752170152
// 官网：https://www.nutpi.net/
// All rights reserved.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'package:flutter/widgets.dart';
import 'package:provider/provider.dart';
import 'providers/health_news_provider.dart';
import 'providers/health_tips_provider.dart';
import 'providers/health_reminder_provider.dart';
import 'providers/nutrition_provider.dart';
import 'widgets/about_page.dart';
import 'widgets/health_news_page.dart';
import 'widgets/health_tips_page.dart';
import 'widgets/health_reminder_page.dart';
import 'widgets/nutrition_page.dart';
import 'providers/theme_provider.dart';
import 'widgets/theme_settings_page.dart';
import 'widgets/weight_management_page.dart';
import 'providers/weight_management_provider.dart';
import 'providers/page_navigation_provider.dart';
import 'widgets/weight_dashboard_widget.dart';

void main() {
  runApp(const HealthApp());
}

class HealthApp extends StatelessWidget {
  const HealthApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => HealthNewsProvider()),
        ChangeNotifierProvider(create: (_) => HealthTipsProvider()),
        ChangeNotifierProvider(create: (_) => HealthReminderProvider()),
        ChangeNotifierProvider(create: (_) => NutritionProvider()),
        ChangeNotifierProvider(create: (_) => ThemeProvider()),
        ChangeNotifierProvider(create: (_) => WeightManagementProvider()),
        ChangeNotifierProvider(create: (_) => PageNavigationProvider()),
      ],
      child: Consumer<ThemeProvider>(
        builder: (context, themeProvider, _) {
          return MaterialApp(
            title: '健康助手',
            debugShowCheckedModeBanner: false,
            theme: themeProvider.getTheme(),
            themeMode: ThemeMode.light,
            home: const HomeScreen(),
            routes: {
              '/theme_settings': (context) => const ThemeSettingsPage(),
              '/about': (context) => const AboutPage(),
            },
          );
        },
      ),
    );
  }
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final List<Widget> _pages = [
    const HomePage(), // 首页/主页
    const HealthNewsPage(), // 资讯页面
    const WeightManagementPage(), // 新增：体重管理页面
    const ThemeSettingsPage(), // 设置页面
    const AboutPage(), // 关于页面
  ];

  @override
  Widget build(BuildContext context) {
    final pageProvider = Provider.of<PageNavigationProvider>(context);
    final currentIndex = pageProvider.currentIndex;

    return Scaffold(
      appBar: AppBar(
        title:
            const Text('健康助手', style: TextStyle(fontWeight: FontWeight.bold)),
        elevation: 2,
        backgroundColor: Theme.of(context).colorScheme.primary,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: Icon(Provider.of<ThemeProvider>(context).isDarkMode
                ? Icons.light_mode
                : Icons.dark_mode),
            tooltip: '切换深色模式',
            onPressed: () {
              Provider.of<ThemeProvider>(context, listen: false).toggleTheme();
            },
          ),
        ],
      ),
      body: _pages[currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: currentIndex,
        selectedItemColor: Theme.of(context).colorScheme.primary,
        unselectedItemColor: Colors.grey,
        selectedFontSize: 14,
        unselectedFontSize: 12,
        iconSize: 26,
        type: BottomNavigationBarType.fixed,
        elevation: 8,
        backgroundColor: Colors.white,
        selectedLabelStyle: const TextStyle(fontWeight: FontWeight.bold),
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: '首页',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.newspaper),
            label: '资讯',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.monitor_weight),
            label: '体重管理',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.settings),
            label: '设置',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.info),
            label: '关于',
          ),
        ],
        onTap: (index) {
          pageProvider.changePage(index);
        },
      ),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.primary,
        foregroundColor: Colors.white,
        title:
            const Text('健康助手', style: TextStyle(fontWeight: FontWeight.bold)),
        elevation: 2,
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: 8.0),
            child: ElevatedButton.icon(
              onPressed: () {
                Navigator.pushNamed(context, '/about');
              },
              icon: const Icon(Icons.info, size: 20),
              label: const Text('关于'),
              style: ElevatedButton.styleFrom(
                foregroundColor: Theme.of(context).colorScheme.primary,
                backgroundColor: Colors.white,
                elevation: 2,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20),
                ),
                padding:
                    const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              ),
            ),
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          indicatorColor: Colors.white,
          labelColor: Colors.white,
          unselectedLabelColor: Colors.white70,
          indicatorWeight: 3,
          labelStyle:
              const TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
          unselectedLabelStyle: const TextStyle(fontSize: 14),
          tabs: const [
            Tab(icon: Icon(Icons.lightbulb), text: '健康小妙招'),
            Tab(icon: Icon(Icons.tips_and_updates), text: '健康提示'),
            Tab(icon: Icon(Icons.food_bank), text: '营养成分'),
          ],
        ),
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: WeightDashboardWidget(),
          ),
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: const [
                // 健康小妙招页面
                Padding(
                  padding: EdgeInsets.all(16.0),
                  child: HealthTipsPage(),
                ),
                // 健康提示页面
                Padding(
                  padding: EdgeInsets.all(16.0),
                  child: HealthReminderPage(),
                ),
                // 营养成分页面
                Padding(
                  padding: EdgeInsets.all(16.0),
                  child: NutritionPage(),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSectionHeader(
      BuildContext context, String title, IconData icon) {
    return Row(
      children: [
        Icon(icon, color: Theme.of(context).primaryColor),
        const SizedBox(width: 8),
        Text(
          title,
          style: Theme.of(context).textTheme.titleLarge?.copyWith(
                fontWeight: FontWeight.bold,
              ),
        ),
      ],
    );
  }
}
